#!/bin/bash

# UBBC服务图片检查测试脚本 (Linux版本)
# 使用curl调用RESTful API进行图片合规性检查

# 默认配置
DEFAULT_SERVER_URL="http://localhost:8080"
DEFAULT_IMAGE_URL="https://ark-project.tos-cn-beijing.ivolces.com/images/view.jpeg"

# 帮助信息
show_help() {
    echo "Usage: $0 [OPTIONS] IMAGE_URL"
    echo ""
    echo "测试UBBC服务的图片检查功能"
    echo ""
    echo "OPTIONS:"
    echo "  -h, --help              显示帮助信息"
    echo "  -s, --server URL        指定服务器地址 (默认: $DEFAULT_SERVER_URL)"
    echo "  -u, --user-id ID        指定用户ID"
    echo "  -v, --verbose           显示详细输出"
    echo "  -t, --timeout SECONDS   设置请求超时时间 (默认: 30秒)"
    echo "  -k, --api-key KEY       设置API密钥"
    echo ""
    echo "EXAMPLES:"
    echo "  $0 https://example.com/image.jpg"
    echo "  $0 -s http://192.168.1.100:8080 -u user123 https://example.com/image.jpg"
    echo "  $0 -v -t 60 https://example.com/large-image.jpg"
    echo ""
}

# 初始化变量
SERVER_URL="$DEFAULT_SERVER_URL"
IMAGE_URL=""
USER_ID=""
VERBOSE=false
TIMEOUT=30
API_KEY=""

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        -s|--server)
            SERVER_URL="$2"
            shift 2
            ;;
        -u|--user-id)
            USER_ID="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        -t|--timeout)
            TIMEOUT="$2"
            shift 2
            ;;
        -k|--api-key)
            API_KEY="$2"
            shift 2
            ;;
        -*)
            echo "错误: 未知选项 $1"
            echo "使用 $0 --help 查看帮助信息"
            exit 1
            ;;
        *)
            if [[ -z "$IMAGE_URL" ]]; then
                IMAGE_URL="$1"
            else
                echo "错误: 只能指定一个图片URL"
                exit 1
            fi
            shift
            ;;
    esac
done

# 验证参数
if [[ -z "$IMAGE_URL" ]]; then
    echo "错误: 必须提供图片URL"
    echo "使用 $0 --help 查看帮助信息"
    exit 1
fi

# 验证URL格式
if [[ ! "$IMAGE_URL" =~ ^https?:// ]]; then
    echo "错误: 图片URL必须以http://或https://开头"
    exit 1
fi

# 构建请求体
if [[ -n "$USER_ID" ]]; then
    REQUEST_BODY="{\"image_url\": \"$IMAGE_URL\", \"user_id\": \"$USER_ID\"}"
else
    REQUEST_BODY="{\"image_url\": \"$IMAGE_URL\"}"
fi

# 显示请求信息
echo "============================================"
echo "UBBC 图片检查测试"
echo "============================================"
echo "服务器地址: $SERVER_URL"
echo "图片URL:    $IMAGE_URL"
if [[ -n "$USER_ID" ]]; then
    echo "用户ID:     $USER_ID"
fi
echo "超时时间:   ${TIMEOUT}秒"
echo "============================================"

if [[ "$VERBOSE" == true ]]; then
    echo "请求体:"
    echo "$REQUEST_BODY" | jq . 2>/dev/null || echo "$REQUEST_BODY"
    echo "============================================"
fi

# 构建curl命令参数
CURL_ARGS=(
    -X POST
    -H "Content-Type: application/json"
    -d "$REQUEST_BODY"
    --connect-timeout "$TIMEOUT"
    --max-time $((TIMEOUT + 10))
)

# 添加API密钥（如果提供）
if [[ -n "$API_KEY" ]]; then
    CURL_ARGS+=(-H "X-API-Key: $API_KEY")
fi

# 添加详细输出选项
if [[ "$VERBOSE" == true ]]; then
    CURL_ARGS+=(-v)
else
    CURL_ARGS+=(-s)
fi

# 添加URL
CURL_ARGS+=("$SERVER_URL/api/v1/check-image")

# 执行请求
echo "发送请求中..."
START_TIME=$(date +%s)

# 执行curl命令并捕获输出和状态码
RESPONSE=$(curl "${CURL_ARGS[@]}")
HTTP_STATUS=$?

END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))

echo "============================================"
echo "响应 (耗时: ${DURATION}秒)"
echo "============================================"

# 检查curl命令是否成功执行
if [[ $HTTP_STATUS -ne 0 ]]; then
    echo "错误: 请求失败 (curl exit code: $HTTP_STATUS)"
    case $HTTP_STATUS in
        6)
            echo "原因: 无法解析主机名"
            ;;
        7)
            echo "原因: 无法连接到服务器"
            ;;
        28)
            echo "原因: 请求超时"
            ;;
        *)
            echo "原因: 网络错误或服务器不可达"
            ;;
    esac
    exit 1
fi

# 尝试格式化JSON响应
if command -v jq >/dev/null 2>&1; then
    echo "$RESPONSE" | jq .
    
    # 提取关键信息
    COMPLIANT=$(echo "$RESPONSE" | jq -r '.["合规"] // .compliant // "unknown"')
    DESCRIPTION=$(echo "$RESPONSE" | jq -r '.["说明"] // .description // "无描述"')
    REQUEST_ID=$(echo "$RESPONSE" | jq -r '.request_id // "unknown"')
    
    echo "============================================"
    echo "检查结果摘要:"
    echo "合规状态: $COMPLIANT"
    echo "说明:     $DESCRIPTION"
    echo "请求ID:   $REQUEST_ID"
    echo "============================================"
    
    # 根据结果设置退出码
    if [[ "$COMPLIANT" == "true" ]]; then
        echo "✅ 图片内容合规"
        exit 0
    elif [[ "$COMPLIANT" == "false" ]]; then
        echo "❌ 图片内容违规"
        exit 2
    else
        echo "⚠️  检查状态未知"
        exit 3
    fi
else
    # 没有jq时直接输出原始响应
    echo "$RESPONSE"
    
    # 简单检查是否包含成功标识
    if [[ "$RESPONSE" == *'"合规":true'* ]] || [[ "$RESPONSE" == *'"compliant":true'* ]]; then
        echo ""
        echo "✅ 图片内容合规"
        exit 0
    elif [[ "$RESPONSE" == *'"合规":false'* ]] || [[ "$RESPONSE" == *'"compliant":false'* ]]; then
        echo ""
        echo "❌ 图片内容违规"
        exit 2
    elif [[ "$RESPONSE" == *'"error"'* ]]; then
        echo ""
        echo "❌ 请求出错"
        exit 1
    else
        echo ""
        echo "⚠️  无法解析响应"
        exit 3
    fi
fi
